﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.ServiceHosting.ServiceRuntime;

namespace HollywoodHackers.Storage.Queue
{
    public class SystemMessageRepository
    {
        private MessageQueue queue;
        private static StorageAccountInfo account;
        private QueueStorage storage;
        
        // this can't be mocked with an underlying mock queue...Needs refactoring
        public SystemMessageRepository(string queueName)
        {
            if (account == null)
            {
                account = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();
            }
            storage = QueueStorage.Create(account);
            storage.RetryPolicy = RetryPolicies.RetryN(2, TimeSpan.FromMilliseconds(100));

            queue = storage.GetQueue(queueName);
            bool exists;
            bool res = queue.CreateQueue(out exists);
            if (!exists)
            {
                RoleManager.WriteToLog("Information",
                    string.Format("Created Queue {0} for First Time.", queueName));
            }
            
        }

        public void EnqueueSystemMessage(SystemMessage msg)
        {
            Message m = new Message(msg.ToBinary());
            queue.PutMessage(m);
        }        

        public void ClearMessages()
        {
            queue.Clear();
        }
    }
}
